import {
  SET_STOCKTAKING_ORDER_LIST,
  SET_STOCKTAKING_LOC_LIST,
  SET_STOCKTAKING_ITEM_LIST,
  UPDATE_STOCKTAKING_ITEM,
  ADD_STOCKTAKING_ITEM,
  UPDATE_STOCKTAKING_ITEM_REAL_QTY,
  CLEAR_STOCKTAKING_ITEM_LIST,
  SET_STOCKTAKING_BARCODE_LIST,
  DEL_STOCKTAKING_BARCODE,
} from "./action-types";

const initialState = {
  orderList: [],
  orderListOffset: 0,

  locList: [],
  itemList: [],
  barcodeList: [],
};

const handleSetOrderList = (state, payload) => {
  let { items, offset } = payload;
  if (items.length === 0 && offset === 0) {
    return { ...state, orderList: [], orderListOffset: 0 };
  } else {
    return {
      ...state,
      orderList: state.orderList.concat(items),
      orderListOffset: offset
    };
  }
};

const handleUpdateItem = (state, payload) => {
  let newItemList = state.itemList.map((i) =>
    i.itemCode === payload.itemCode ? payload : i
  );
  return { ...state, itemList: newItemList };
};

const handleUpdatgeRealQty = (state, payload) => {
  let { id, realQty } = payload;
  const idx = state.itemList.findIndex((item) => item.id === id);
  if (idx !== -1) {
    const updateItems = [...state.itemList];
    updateItems[idx] = {
      ...updateItems[idx],
      realQty,
    };

    return {
      ...state,
      itemList: updateItems,
    };
  }
  return state;
};

const data = (state = initialState, action) => {
  switch (action.type) {
    case SET_STOCKTAKING_ORDER_LIST:
      return handleSetOrderList(state, action.payload);
    case SET_STOCKTAKING_LOC_LIST:
      return { ...state, locList: action.payload.items };
    case SET_STOCKTAKING_ITEM_LIST:
      return { ...state, itemList: action.payload.items };
    case UPDATE_STOCKTAKING_ITEM:
      return handleUpdateItem(state, action.payload);
    case ADD_STOCKTAKING_ITEM:
      return { ...state, itemList: [...state.itemList, action.payload] };
    case UPDATE_STOCKTAKING_ITEM_REAL_QTY:
      return handleUpdatgeRealQty(state, action.payload);
    case CLEAR_STOCKTAKING_ITEM_LIST:
      return { ...state, itemList: [] };
    case SET_STOCKTAKING_BARCODE_LIST:
      return { ...state, barcodeList: action.payload.items };
    case DEL_STOCKTAKING_BARCODE:
      return {
        ...state,
        barcodeList: state.barcodeList.filter(
          (i) => i.id !== action.payload.id
        ),
      };
    default:
      return state;
  }
};

export default data;
